package com.chenwut.myreflect.a05_reflect_exercise_1;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;

/**
 * @author ChenPi
 * @since 2024/09/23 17:21
 */
public class MyReflectDemo {
    public static void main(String[] args) throws IllegalAccessException, IOException {

        /**
         * 对于任意一个对象，都可以把对象所有的字段名和值，保存到文件中去
         */
        Student s = new Student("小A", 23, '女', 167.5, "睡觉");
        Teacher t = new Teacher("波妞", 1000);
        saveObject(s);

    }

    /**
     * 把对象里面所有的成员变量名和值保存到本地文件中
     */
    public static void saveObject(Object obj) throws IllegalAccessException, IOException {
        Class clazz = obj.getClass();

        BufferedWriter writer = new BufferedWriter(new FileWriter(".\\SE_Code\\src\\com\\chenwut\\myreflect\\a.txt"));
        Field[] fields = clazz.getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            String name = f.getName();
            Object value = f.get(obj);
            writer.write(name + ":" + value);
            writer.newLine();
        }
        writer.close();
    }
}
